#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-10 下午4:08
import json
import sqlite3

from flask import Flask, g


app = Flask(__name__)

DATABASE = 'data.db'


def make_dicts(cursor, row):
    return dict((cursor.description[idx][0], value) for idx, value in enumerate(row))


def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    # db.row_factory = make_dicts
    db.row_factory = sqlite3.Row
    return db


def query_db(query, args=(), one=False):
    cur = get_db().execute(query, args)
    rv = cur.fetchall()
    cur.close()
    return (rv[0] if rv else None) if one else rv


@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db:
        db.close()


@app.route('/initdb')
def initdb():
    db = get_db()
    with app.open_resource("schema.sql") as f:
        db.cursor().executescript(f.read())
    db.commit()
    return 'init db successfully!'


@app.route('/')
def index():
    ret = []
    for user in query_db('select * from users'):
        print user
        ret.append({
            "id": user['id'],
            "username": user['username'],
            "email": user['email']
        })
    return json.dumps(ret)


if __name__ == '__main__':
    app.run(debug=True)